import React, { Fragment } from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Select, Divider,  Checkbox } from 'antd';
import { routerRedux } from 'dva/router';
import styles from './style.less';
import UserSelect from '../UserSelect';

const { Option } = Select;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};

@connect(({ testrecord, project, version, loading }) => ({
  currentProject: project.currentProject,
  currentUserOwnedProjectList: project.currentUserOwnedProjectList,
  versions: version.list,
  currentVersion: version.currentVersion,
  formData: testrecord.formData,
  loading: loading.models.testrecord
}))
export default Form.create()(
  class extends React.PureComponent {

    componentDidMount(){
      let params = this.props.location.state;
      this.props.dispatch({
        type: 'project/queryCurrentUserOwnedProjects',
        payload: params
      });  
    }

    configProjectOption = (projects) => {
      let options = projects.map( p => {
        return <Option key={`${p.id}-${p.name}`} value={p.id}>{`${p.name}`}</Option>
      });
      return options;
    }

    configVersionOptions = (versions) => {
      let options = versions.map( v => {
        return <Option key={`${v.id}-${v.name}`} value={v.id}>{`${v.name}`}</Option>
      });
      return options;
    }
  
    getUserSelect = (roleId, users) => {
      return <UserSelect roleId={roleId} holder="" users={users} disabled={true}/>
    }

    handleProjectSelect = (value) => {
      let formData = this.props.formData;
      this.props.form.resetFields(['versionId'])
      this.props.dispatch({
        type:'version/queryByProjectId',
        payload: _.toInteger(value)
      });
      this.props.dispatch({
        type:'project/query',
        payload: _.toInteger(value)
      })
      if(!_.isEmpty(formData)){
        delete formData.version;
        delete formData.project;
      }
      this.props.dispatch({
        type:'testrecord/saveFormData',
        payload: formData
      })
    }

    handleVersionSelect = (value, option) => {
      this.props.dispatch({
        type:'version/setCurrentVersion',
        payload: {id:value, name:option.props.children}
      })
    }

    nextStep = () => {
      let project = this.props.currentProject;
      let version = this.props.currentVersion;

      this.props.form.validateFields((err, values) => {
        if (!err) {
          this.props.dispatch({
            type: 'testrecord/saveFirstStepFormData',
            payload: {...values, project, version}
          });
          this.props.dispatch(routerRedux.push('/testcenter/testsubmit/confirm'));
        }
      });
    };
  
    render() {
      const { currentUserOwnedProjectList, currentProject, versions,currentVersion, formData} = this.props;
      const { getFieldDecorator} = this.props.form;
      return (
        <Fragment>
          <Form layout="horizontal" className={styles.stepForm} hideRequiredMark>
            <Form.Item {...formItemLayout} label="提测项目">
              {getFieldDecorator('projectId', {
                rules: [{ required: true, message: '请选择提测项目' }],
                initialValue: formData.project ? formData.project.id : currentProject.id
              })(
                <Select style={{ width: 150 }} onSelect={this.handleProjectSelect}>
                  {this.configProjectOption(currentUserOwnedProjectList)}
                </Select>
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="提测版本">
            {getFieldDecorator('versionId', {
                rules: [{ required: true, message: '请选择提测版本' }],
                initialValue: formData.version ? formData.version.id : (currentVersion ?  currentVersion.id : null)
              })(
                <Select style={{ width: 150 }} onSelect={this.handleVersionSelect} >
                  {this.configVersionOptions(versions)}
                </Select>
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="测试">
              {getFieldDecorator('tester', {
              })(
                <UserSelect roleId={3} holder="" users={formData.project ? formData.project.tester : currentProject.tester} disabled={true}/>
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="开发">
              {getFieldDecorator('developer', {
              })(
                <UserSelect roleId={2} holder="" users={formData.project ? formData.project.developer : currentProject.developer} disabled={true}/>
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="产品">
              {getFieldDecorator('pm', {
              })(
                <UserSelect roleId={1} holder="" users={formData.project ? formData.project.pm : currentProject.pm} disabled={true}/>
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="新功能">
              {getFieldDecorator('newFeatureRemark', {
                initialValue: formData.newFeatureRemark ? formData.newFeatureRemark : '',
                rules: [
                  { required: true, message: '请输入本次迭代版本的新功能' },
                ],
              })(<TextArea autosize={{ minRows: 3 }} placeholder="请简要描述本次迭代版本的新功能" />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="修改点">
              {getFieldDecorator('updateRemark', {
                initialValue: formData.updateRemark ? formData.updateRemark : '',
                rules: [
                  { required: true, message: '请输入本次迭代版本的修改点' },
                ],
              })(<TextArea autosize={{ minRows: 3 }} placeholder="请简要描述本次迭代版本的修改点" />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="备注">
              {getFieldDecorator('adviseRemark', {
                initialValue: formData.adviseRemark ? formData.adviseRemark : '',
                rules: [
                  { required: true, message: '请输入本次迭代版本的建议' },
                ],
              })(
                <TextArea
                  autosize={{ minRows: 3 }}
                  placeholder="关于本次迭代版本的测试建议&备注（如：已知问题等）"
                />
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label={<a href="#">自测用例</a>}>
              {getFieldDecorator('selfTestStatus', {
                valuePropName: 'checked',
                initialValue: formData.selftestresult,
                rules: [{ required: true, message: '请确认自测用例执行结果为全部通过' }],
              })(<Checkbox>全部通过</Checkbox>)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="提测包(地址)">
              {getFieldDecorator('testPackageUrl', {
                initialValue: formData.testPackageUrl ? formData.testPackageUrl : '',
                rules: [
                  { required: true, message: '请输入本次迭代版本的获取路径' },
                ],
              })(<TextArea autosize={{ minRows: 3 }} placeholder="客户端提测包路径/web端测试地址" />)}
            </Form.Item>
            <Form.Item
              wrapperCol={{
                xs: { span: 24, offset: 0 },
                sm: {
                  span: formItemLayout.wrapperCol.span,
                  offset: formItemLayout.labelCol.span,
                },
              }}
              label=""
            >
              <Button type="primary" onClick={this.nextStep}>
                下一步
              </Button>
            </Form.Item>
          </Form>
          <Divider style={{ margin: '40px 0 24px' }} />
          <div className={styles.desc}>
            <h3>提测原则</h3>
            <h4>基本提测标准</h4>
            <p>1. 本次迭代/集成的需求功能都开发完成（客户端/前端、服务端/后端）<br /></p>
            <p>2. 前、后端对接调试完成，并要保证后台环境稳定；<br /></p>
            <p>3. 测试所需的真实数据都准备好；<br /></p>
            <p>4. 测试接到提测包会进行一轮<span style={{ color: 'red' }}>
                快速测试</span>（15-30min）：<br /></p>
                <p style={{ textIndent: 35 }}>- 发现致命的BUG并阻碍测试进程，则将本次提测打回；</p>
                <p style={{ textIndent: 35 }}>- 发现严重并紧急的Bug超过3个，则将本次提测打回；</p>
                <p style={{ textIndent: 35 }}>- 发现部分核心需求功能未开发完成，则将本次提测打回；</p>
                <p style={{ textIndent: 35 }}>- 发现部分功能实现与需求严重不符合的，则将本次提测打回；</p>
            
            <h4>回归提测要求</h4>
            <p>
              1.
              修复80%以上的Bug，才可以提交一轮回归测试（原则上需修复所有Bug才能提测，个别特殊情况除外）；<br />
              2. Bug回归通过率低于60%，则该轮回归测试被打回；<br />
              3. 回归测试包中新引入严重并紧急的Bug超过3个，则该轮回归测试被打回；<br />
              4. 回归测试包中新引入致命Bug，则该轮回归测试被打回；
            </p>
          </div>
        </Fragment>
      );
    }
  }
);
